<template>
  <view class="user-list">
    <view class="title">{{ title }}（{{ total }}）</view>
    <view v-if="list.length === 0" class="empty">暂无数据</view>
    <view v-else>
      <view class="user-item" v-for="item in list" :key="item._id">
        <image class="avatar" :src="item.avatar" mode="aspectFill" />
        <text class="nickname">{{ item.nickname }}</text>
        <view class="flex-spacer"></view>
        <button class="message-btn" @click="goToChat(item._id)">私信</button>
        <button v-if="type === 'follow'" class="unfollow-btn" @click="handleUnfollow(item._id)">取消关注</button>
      </view>
    </view>
  </view>
</template>

<script>
import { fetchAndCacheFollowFansCount } from '@/utils/followCache'

export default {
  data() {
    return {
      list: [],
      total: 0,
      title: '',
      type: 'follow',
      userId: '',
      page: 1,
      finished: false,
      loading: false
    }
  },
  onLoad(options) {
    this.type = options.type || 'follow'
    this.title = this.type === 'follow' ? '我的关注' : '我的粉丝'
    // 获取当前用户id
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.userId) {
      this.userId = userInfo.userId
      this.fetchList()
    } else {
      uni.showToast({ title: '请先登录', icon: 'none' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }
  },
  onPullDownRefresh() {
    this.refreshList()
  },
  onReachBottom() {
    if (this.finished || this.loading) return
    this.page++
    this.fetchList()
  },
  methods: {
    async fetchList(refresh = false) {
			if (this.finished) return
			const userObj = uniCloud.importObject('user', {
				customUI: true
			})
			const res = await userObj.getUserProfileWithFollowInfo({
				userId: this.userId,
				type: this.type,
				page: this.page,
				pageSize: 100 // 可根据需要分页
			})
      if (res.code === 200) {
        if (refresh) {
          this.list = res.data.list
          this.total = res.data.total
        } else {
          this.list = [...this.list, ...res.data.list]
          this.total = res.data.total
        }
        this.page++
        if (res.data.list.length < 100) {
          this.finished = true
        }
      } else {
        this.list = []
        this.total = 0
        this.finished = true
      }
    },
    async refreshList() {
      this.page = 1
      this.finished = false
      await this.fetchList(true)
      uni.stopPullDownRefresh()
    },
    async handleUnfollow(followeeId) {
      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo || !userInfo.userId) {
        uni.navigateTo({ url: '/pages/login/login' })
        return
      }
      uni.showModal({
        title: '提示',
        content: '确定要取消关注吗？',
        success: async (res) => {
          if (res.confirm) {
            const userObj = uniCloud.importObject('user', { customUI: true })
            const result = await userObj.unfollowUser({
              followerId: userInfo.userId,
              followeeId
            })
            if (result.code === 200) {
              uni.showToast({ title: '已取消关注', icon: 'success' })
              // 刷新本地缓存的关注和粉丝数量
              fetchAndCacheFollowFansCount(userInfo.userId)
              this.page = 1
              this.finished = false
              await this.fetchList(true)
            } else {
              uni.showToast({ title: result.msg || '操作失败', icon: 'none' })
            }
          }
        }
      })
    },
    goToChat(targetUserId) {
      uni.navigateTo({
        url: `/pages/chat/chat?targetUserId=${targetUserId}`
      })
    }
  }
}
</script>

<style lang="scss">
.user-list {
  padding: 30rpx;
  .title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }
  .empty {
    color: #999;
    text-align: center;
    margin-top: 100rpx;
  }
  .user-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 40rpx;
      margin-right: 20rpx;
    }
    .nickname {
      font-size: 28rpx;
      color: #333;
    }
    .message-btn {
      background: #fff;
      color: #1890ff;
      border: 1px solid #1890ff;
      border-radius: 32rpx;
      font-size: 26rpx;
      padding: 10rpx 36rpx;
      margin-left: 20rpx;
      transition: background 0.2s, color 0.2s, border 0.2s;
      outline: none;
      box-shadow: none;
      cursor: pointer;
      min-width: 100rpx;
      text-align: center;
    }
    .message-btn:active {
      background: #e6f7ff;
      color: #096dd9;
      border-color: #096dd9;
    }
    .unfollow-btn {
      background: #fff;
      color: #ff4d4f;
      border: 1px solid #ff4d4f;
      border-radius: 32rpx;
      font-size: 26rpx;
      padding: 10rpx 36rpx;
      margin-left: 20rpx;
      transition: background 0.2s, color 0.2s, border 0.2s;
      outline: none;
      box-shadow: none;
      cursor: pointer;
      min-width: 120rpx;
      text-align: center;
    }
    .unfollow-btn:active {
      background: #ffeaea;
      color: #d9363e;
      border-color: #d9363e;
    }
  }
  .flex-spacer {
    flex: 1;
  }
}
</style>